// pages/pay/index.js

import { chooseAddress,getSetting,openSetting,requestPayment,showToast } from "../../utils/asyncWx.js"
import regeneratorRuntime from '../../lib/runtime/runtime'
import { request } from '../../request/index.js'

Page({
  data: {
      address: {},
      cart:[],
      totalPrice:0,
      totalNum:0
    },
  onLoad: function (options) {

    },
  onShow(){
    //1 获取缓存中的收货地址信息
    const address = wx.getStorageSync("address");

    //2 获取缓存中的购物车数据
    let cart = wx.getStorageSync("cart") || [];

    //过滤后的购物车数组
    cart = cart.filter(v => v.checked)
	
    //3 计算 总价格、总数量
    
    //总价格和总数量
    let totalPrice = 0
    let totalNum = 0
    cart.forEach(v =>{
        totalPrice += v.num * v.goods_price
        totalNum += v.num
    })

    //3 将数据保存到 data中
    this.setData({
      address,
      cart,
      totalPrice,
      totalNum
    })
	
  },

  //点击 支付按钮
  async handleOrderPay(){
    try{
      
      //1 判断缓存中有没有token
      const token = wx.getStorageSync('token')
      //2 判断
      if(!token){
        wx.navigateTo({
          url: '/pages/auth/index'
        })
      
        return
      }
      //console.log('已经存在token~')
      
      //3 创建订单
      //3.1 准备 请求头 参数 
      //const header = { Authorization:token }
      
      //3.2 准备 请求体 参数
      const order_price = this.data.totalPrice
      const consignee_addr = this.data.address
      
      const cart = this.data.cart
      let goods = []
      cart.forEach(v => goods.push({
        goods_id:v.goods_id, 
        goods_number:v.num, 
        goods_price:v.goods_price
      }))
      
      const orderParams = {order_price, consignee_addr, goods}
      
      //4 准备发送请求创建订单获取订单编号
      const { order_number } = await request({
        url: '/my/orders/create',
        method: 'POST',
        data: orderParams
        // header: header
        //header  //简写
      })
      //console.log('订单编号：' + order_number)
      
      //5 发起预支付接口 
      const { pay } = await request({
        url: '/my/orders/req_unifiedorder',
        method: 'POST',
        //header,
        data: {order_number}
      })
      //console.log(res)
      
      //6 发起 微信支付
      await requestPayment(pay)
      
      //const res = await requestPayment(pay)
      //console.log(res)
      
      //7 查询 后台 订单状态
      const res = await requset({
        url: '/my/orders/chkOrder',
        method: 'POST',
        //header,
        data: {order_number}
      })
      //console.log(res);

      await showToast({title: "支付成功"})

      //8 手动删除 缓存中 完成支付的 商品数据
      let newCart = wx.getStorageSync("cart");
      newCart = newCart.filter(v => !v.checked)

      //9 将新购物车数组 设置回 缓存中
      wx.setStorageSync("cart", newCart);

      //10 支付完成 跳转到 订单页面
      wx.navigateTo({
        url: '/pages/order/index'
      })
        
      
    }catch(error){
      console.log(error);
      await showToast({title: "支付失败"})
    }
  }

})

